package com.datastructure.test.zigzagoutputstring;

public class ZigzagOutputString {

    public static void main(String[] args) {
        ZigzagOutputString zigzagOutputString = new ZigzagOutputString();
        zigzagOutputString.zconvert("nowcodernowcoder",3);
    }

    public String zconvert1 (String str, int k) {
        // write code here
        StringBuilder stringBuilder = new StringBuilder();
        int mode = 2*k-2;
        int length = str.length();
        char[][] temp = new char[k][(k-1)*(length/mode+1)];
        char[] charArray = str.toCharArray();
        int i = 0;
        int j = 0;
        int index = 0;
        do {
            while (i < k) {
                if (index == length) {
                    break;
                }
                temp[i][j] = charArray[index];
                index++;
                i++;
            }
            i-=2;
            j++;
            while (i >= 0) {
                if (index == length) {
                    break;
                }
                temp[i][j] = charArray[index];
                index++;
                i--;
                if(i!=-1){
                    j++;
                }
            }
            i+=2;
        } while (index != length);
        for (char[] chars : temp) {
            for (char c : chars) {
                if(c!='\u0000'){
                    stringBuilder.append(c);
                }
            }
        }
        return stringBuilder.toString();
    }

    public String zconvert (String str, int k) {
        StringBuilder stringBuilder = new StringBuilder();
        int mode = 2*k-2;
        int length = str.length();
        char[][] temp = new char[k][(k-1)*(length/mode+1)];
        char[] charArray = str.toCharArray();
        int i = 0;
        int j = 0;
        int index = 0;
        do {
            while (i < k) {
                if (index == length) {
                    break;
                }
                temp[i][j] = charArray[index];
                index++;
                i++;
            }
            i-=2;
            j++;
            while (i >= 0) {
                if (index == length) {
                    break;
                }
                temp[i][j] = charArray[index];
                index++;
                i--;
                if(i!=-1){
                    j++;
                }
            }
            i+=2;
        } while (index != length);
        for (char[] chars : temp) {
            for (char c : chars) {
                if(c!='\u0000'){
                    stringBuilder.append(c);
                }
            }
        }
        return stringBuilder.toString();
    }
}
